package org.xmlpersist.util;

import java.util.*;
import java.io.*;

/***
 * Loading database properties file either from classpath or from specified file
 * location
 * 
 * @author sheik882
 * 
 */
public class DBPropertiesLoader {

	private static String filePath = null;
	
	private InputStream inputStream = null;

	private Properties properties = null;

	public DBPropertiesLoader() {

	}

	/***
	 * Setting file path explicitly
	 * 
	 * @param filePath
	 */
	public DBPropertiesLoader(String filePath) {
		this.filePath = filePath;
	}

	public Map<String, String> getDBInfo() {

		properties = new Properties();
		try {
			properties.load(loadPropertiesFile());
		} catch (IOException e) {
			e.printStackTrace(); // log
		}
		Map<String, String> propMap = new HashMap<String, String>(
				(Map) properties);
		return propMap;
	}

	public InputStream loadPropertiesFile() {

		try {
			if (filePath == null) {
				inputStream = this.getClass().getClassLoader()
						.getResourceAsStream("xmlpersist.cfg.properties");
				if (inputStream == null)
					throw new FileNotFoundException(
							"XMLPersist : could not find property file xmlpersist.cfg.properties");

			} else {

				inputStream = this.getClass().getClassLoader()
						.getResourceAsStream(filePath);
				if (inputStream == null)
					throw new FileNotFoundException(
							"XMLPersist : could not find property file "
									+ filePath);

			}
			return inputStream;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println("Exception ----------> " + e);
			e.printStackTrace();
		}

		return inputStream;
	}

	public static void setFilePath(String filePath) {
		DBPropertiesLoader.filePath = filePath;
	}

}
